﻿#include "FSingleLineEditDialog.h"
#include "ui_FSingleLineEditDialog.h"

#include <QLabel>


FSingleLineEditDialog::FSingleLineEditDialog(QWidget *parent)
    : FDialog(parent)
    , ui(new Ui::FSingleLineEditDialog)
{
    ui->setupUi(this);
    setModal(false);
}

FSingleLineEditDialog::~FSingleLineEditDialog()
{
    delete ui;
}

QString FSingleLineEditDialog::getString(QWidget *parent, const QString &title, const QString &tip, const QString &defaultVal, QRegExpValidator* validator)
{
    FSingleLineEditDialog dialog(parent);
    dialog.setWindowTitle(title);

    FLineEdit* edit = dialog.addEdit(tip, defaultVal);

    if (validator) {
        edit->setValidator(validator);
    }

    if (dialog.exec() == QDialog::Accepted) {
        return edit->text().trimmed();
    }

    return QString();
}

int FSingleLineEditDialog::getInt(QWidget *parent, const QString &title, const QString &tip, const int defaultVal, bool *ok)
{
    QRegExpValidator validator(QRegExp("-?[0-9]{8}"));
    QString numStr = FSingleLineEditDialog::getString(parent, title, tip, QString::number(defaultVal), &validator);
    if (numStr.isEmpty()) {
        if (ok) *ok = false;
        return 0;
    }
    bool ok2 = true;
    int num = numStr.toInt(&ok2);
    if (ok2) {
        if (ok) *ok = true;
        return num;
    } else {
        if (ok) *ok = false;
        return 0;
    }
}

QStringList FSingleLineEditDialog::getStrings(QWidget *parent, const QString &title, const QStringList &tips, const QStringList &defaultVals)
{
    QStringList res;

    FSingleLineEditDialog dialog(parent);
    dialog.setWindowTitle(title);

    QList<FLineEdit*> edits;

    for (int i = 0; i < tips.length(); i++) {
        QString dv;
        if (defaultVals.length() > i) dv = defaultVals[i];
        edits.append(dialog.addEdit(tips[i], dv));
    }

    if (dialog.exec() == QDialog::Accepted) {
        for (const auto& edit : edits) {
            res.append(edit->text().trimmed());
        }
    }

    return res;
}

FLineEdit* FSingleLineEditDialog::addEdit(const QString &tip, const QString &defaultVal)
{
    FLineEdit* edit = new FLineEdit(this);
    edit->setText(defaultVal);

    QLabel* label = new QLabel(tip, this);
    // label->setAlignment(Qt::AlignCenter);

    if (tip.isEmpty()) label->setVisible(false);

    ui->editsLayout->addWidget(label);
    ui->editsLayout->addWidget(edit);

    return edit;
}

void FSingleLineEditDialog::on_btnConfirm_clicked()
{
    accept();
}


void FSingleLineEditDialog::on_btnCancel_clicked()
{
    reject();
}

